<?php
namespace Modules\Ddtalk\Lib;

use S\Http;

/**
 * @description 通用基础工具类
 */
class Util {
	const API_URL_BASE      = 'https://oapi.dingtalk.com';

	public static $timeout  = 3000;

	/**
	 * 代理服务器配置，false为不使用，true为使用默认代理服务器
	 * @var bool
	 */
	public static $proxy_switch = true;

	/**
	 * 发起调用微信服务请求
	 *
	 * @param string        $path  路径或url
	 * @param array         $data
	 * @param bool          $need_access_token
	 * @param bool|string   $http_method
	 * @return bool|mixed
	 * @throws Exception
	 */
	public static function request($path, $data=array(), $need_access_token=true, $http_method=false) {
		$ret = self::call($path, $data, $need_access_token, false, $http_method);
		// token 无效重试一次，更新access token，重试一次
		$errcode = isset($ret['errcode']) ? (int)$ret['errcode'] : 0;
		if ($errcode === 40001 || $errcode === 42001) {
			usleep(300000);
			$ret = self::call($path, $data, $need_access_token, true, $http_method);
		}

		if ($ret && !empty($ret['errcode'])) {
            throw new Exception($ret['errmsg'], $ret['errcode']);
		}

        return $ret;
	}

    /**
     * 对原文进行json序列化
     *
     * @param mixed $data 原文
     *
     * @return string
     */
    public static function json_encode($data) {
		return json_encode($data, JSON_UNESCAPED_UNICODE);
	}

    /**
     * 发送http请求
     *
     * @param $path
     * @param array $data
     * @param bool $need_access_token
     * @param bool $access_token_reset
     * @param bool $http_method
     *
     * @return bool|array
     * @throws Exception
     */
    protected static function call($path, $data=array(), $need_access_token=true, $access_token_reset=false, $http_method=false) {
        $url = $path[0] === '/' ? self::API_URL_BASE.$path : $path;

        if ($need_access_token) {
            $token = AccessToken::get(false, $access_token_reset);
            if (!$token) {
                throw new Exception('get access_token fail', Exception::UNKNOW_ERROR);
            }
            $url .= '?' . 'access_token='.$token;
        }

	    $headers     = array('Content-Type'=>'application/json');
        $http_method = is_string($http_method) ? strtolower($http_method) : $http_method;
        //失败重试两次
        $ret = false;
        for ($i = 0; $i < 3; $i++) {
            if (!$data || $http_method === 'get') {
                $ret = Http::request($url, 'GET', $data, Http::TIMEOUT, '', $headers, false);
            } elseif ($http_method === 'post') {
	            $ret = Http::request($url, 'POST', $data, Http::TIMEOUT, '', $headers, false);
            } else {
	            $ret = Http::request($url, 'POST', array(self::json_encode($data)), Http::TIMEOUT, '', $headers, false);
            }
            if ($ret) {
                break;
            }
        }

        return empty($ret) ? $ret : json_decode($ret, true);
    }

}